<template>
  <div 
    :class="componentClasses"
    :style="componentStyles"
    :data-component-id="component.id"
    :data-component-type="component.type"
    @click="handleClick"
    @dblclick="handleDoubleClick"
    @dragstart="handleDragStart"
    @dragover="handleDragOver"
    @drop="handleDrop"
    @dragleave="handleDragLeave"
    @mouseenter="handleMouseEnter"
    @mouseleave="handleMouseLeave"
    @mousemove="handleMouseMove"
  >
    <!-- 组件选择边框 -->
    <div 
      v-if="isSelected"
      class="component-selection-border"
      @click.stop
    >
      <!-- 选中指示器 -->
      <!-- <div class="selection-indicator">
        <div class="indicator-dot"></div>
        <span class="indicator-text">已选中</span>
      </div> -->
      
      <!-- 层级信息显示 -->
      <div class="layer-info">
        <span class="layer-badge">第{{ getComponentLayer() }}层</span>
      </div>
      
      <div class="selection-handles">
        <div class="handle handle-nw" @mousedown.stop="(event) => startResize('nw', event)"></div>
        <div class="handle handle-ne" @mousedown.stop="(event) => startResize('ne', event)"></div>
        <div class="handle handle-sw" @mousedown.stop="(event) => startResize('sw', event)"></div>
        <div class="handle handle-se" @mousedown.stop="(event) => startResize('se', event)"></div>
      </div>
    </div>

    <!-- 组件内容 -->
    <div class="component-content">
      <!-- 根据组件类型渲染不同的内容 -->
  <component
        :is="getComponentByType(component.type)"
        v-bind="getComponentProps(component)"
        :is-selected="isSelected"
        :style="innerComponentStyle"
        :class="{ 'component-preview': isPreview }"
        :children="component.children"
      >
        <!-- 按钮组件的文本内容 -->
        <template v-if="component.type === 'button' && component.props?.text">
          {{ component.props.text }}
        </template>
        
        <!-- 递归渲染子组件 -->
        <template v-if="component.children && component.children.length">
          <ComponentRenderer
            v-for="child in component.children"
            :key="child.id"
            :component="child"
            :is-selected="isChildSelected(child)"
            :is-preview="isPreview"
            @click="handleChildClick"
            @dblclick="handleChildDoubleClick"
            @drag-start="handleChildDragStart"
            @update="handleChildUpdate"
            @delete="handleChildDelete"
          />
        </template>
      </component>
    </div>

    <!-- 组件标签 -->
    <div v-if="!isPreview && (isHovered || isSelected)" class="component-label">
      <span class="label-text">{{ component.name || component.type }}</span>
      <!-- 调试信息 -->
      <!-- <small v-if="debugMode" style="font-size: 10px; color: #fff; margin-left: 4px;">
        {{ component.name ? `name: ${component.name}` : `type: ${component.type}` }}
        <br>ID: {{ component.id }}
        <br>updatedAt: {{ component.updatedAt }}
      </small> -->
    </div>

    <!-- 拖拽高亮 -->
    <div 
      v-if="isDragOver && canAcceptDrop"
      class="drag-overlay"
    >
      <div class="drop-zone">
        <i class="el-icon-plus"></i>
        <span>放置到此处</span>
      </div>
    </div>
    

  </div>
</template>

<script setup>
import { computed, ref, inject, onMounted, onUnmounted } from 'vue'
import { useDragDropManager } from '@/composables/useDragDropManager'
import TextWidget from '../widgets/TextWidget.vue'
import ButtonWidget from '../widgets/ButtonWidget.vue'
import ImageWidget from '../widgets/ImageWidget.vue'
import ContainerWidget from '../widgets/ContainerWidget.vue'

// Props
const props = defineProps({
  component: {
    type: Object,
    required: true
  },
  isSelected: {
    type: Boolean,
    default: false
  },
  isPreview: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits([
  'click',
  'dblclick',
  'drag-start',
  'update',
  'delete',
  'drag-target-highlight'
])

// 注入的依赖
const designerStore = inject('designerStore')
const selectedComponent = inject('selectedComponent')
const dragDropManager = inject('dragDropManager')

// 调试模式
const debugMode = ref(true)

// 拖拽管理器
const { canAcceptDrop: checkCanAcceptDrop } = useDragDropManager()

// 响应式状态
const isDragOver = ref(false)
const isResizing = ref(false)
const resizeDirection = ref('')
const resizeStartPos = ref({ x: 0, y: 0 })
const resizeStartSize = ref({ width: 0, height: 0 })
const isHovered = ref(false)
const isNearResizeHandle = ref(false) // 新增：是否在 resize handle 附近

// 鼠标事件处理
const handleMouseEnter = () => {
  isHovered.value = true
}

const handleMouseLeave = () => {
  isHovered.value = false
  isNearResizeHandle.value = false // 离开时重置状态
}

const handleMouseMove = (event) => {
  // 性能优化：只在选中状态下检测
  if (!props.isSelected) {
    isNearResizeHandle.value = false
    return
  }
  
  // 检测鼠标是否在 resize handle 附近
  const nearHandle = isMouseNearResizeHandle(event.clientX, event.clientY)
  
  // 状态变化时记录日志
  if (nearHandle !== isNearResizeHandle.value) {
    console.log('handleMouseMove: resize handle 状态变化', { 
      nearHandle, 
      componentId: props.component.id,
      mousePos: { x: event.clientX, y: event.clientY }
    })
  }
  
  isNearResizeHandle.value = nearHandle
}

// 计算属性
const componentClasses = computed(() => [
  'component-renderer',
  `component-${props.component.type}`,
  {
    'is-selected': props.isSelected,
    'is-dragging': dragDropManager.isDragging.value,
    'is-drag-over': isDragOver.value,
    'is-preview': props.isPreview,
    'is-near-resize-handle': isNearResizeHandle.value // 新增：鼠标在 resize handle 附近时的状态
  }
])

const componentStyles = computed(() => {
  // 外层仅保留非定位类样式（主要用于尺寸等），定位由画布外层容器负责
  const style = { ...(props.component.style || {}) }
  delete style.position
  delete style.left
  delete style.top
  delete style.right
  delete style.bottom
  delete style.zIndex
  return style
})

// 内部真实渲染组件的样式：同样去除定位相关字段，避免二次偏移
const innerComponentStyle = computed(() => {
  const style = { ...(props.component.style || {}) }
  delete style.position
  delete style.left
  delete style.top
  delete style.right
  delete style.bottom
  delete style.zIndex
  return style
})

const canAcceptDrop = computed(() => {
  if (!dragDropManager.isDragging.value || !dragDropManager.dragComponent.value) {
    return false
  }
  
  return checkCanAcceptDrop(props.component, dragDropManager.dragComponent.value)
})

// 判断是否为容器组件
const isContainerComponent = computed(() => {
  return props.component.type === 'container' && 
         props.component.children && 
         Array.isArray(props.component.children)
})

// 获取组件层级
const getComponentLayer = () => {
  // 通过DOM结构计算层级
  if (typeof window !== 'undefined') {
    const element = document.querySelector(`[data-component-id="${props.component.id}"]`)
    if (element) {
      let layer = 1
      let parent = element.parentElement
      
      // 向上查找，直到找到画布容器
      while (parent && !parent.classList.contains('canvas-content')) {
        if (parent.classList.contains('component-renderer')) {
          layer++
        }
        parent = parent.parentElement
      }
      
      return layer
    }
  }
  
  // 备用方案：通过组件数据结构计算
  let layer = 1
  let currentComponent = props.component
  
  // 查找父组件
  if (designerStore && designerStore.currentPage) {
    const findParentComponent = (components, targetId) => {
      for (const comp of components) {
        if (comp.children && comp.children.some(child => child.id === targetId)) {
          return comp
        }
        if (comp.children) {
          const found = findParentComponent(comp.children, targetId)
          if (found) return found
        }
      }
      return null
    }
    
    const parent = findParentComponent(designerStore.currentPage.components, currentComponent.id)
    if (parent) {
      layer = 2 // 至少是第2层
    }
  }
  
  return layer
}

// 组件类型映射
const componentTypeMap = {
  text: TextWidget,
  button: ButtonWidget,
  image: ImageWidget,
  container: ContainerWidget,
  input: 'el-input',
  select: 'el-select',
  textarea: 'el-input',
  checkbox: 'el-checkbox',
  radio: 'el-radio',
  switch: 'el-switch',
  slider: 'el-slider',
  datepicker: 'el-date-picker',
  timepicker: 'el-time-picker',
  colorpicker: 'el-color-picker',
  upload: 'el-upload',
  table: 'el-table',
  form: 'el-form',
  card: 'el-card',
  dialog: 'el-dialog',
  drawer: 'el-drawer',
  menu: 'el-menu',
  tabs: 'el-tabs',
  steps: 'el-steps',
  progress: 'el-progress',
  badge: 'el-badge',
  avatar: 'el-avatar',
  tag: 'el-tag',
  divider: 'el-divider'
}

// 方法
const getComponentByType = (type) => {
  return componentTypeMap[type] || 'div'
}

const getComponentProps = (component) => {
  const { type, props: componentProps } = component
  
  // 根据组件类型处理属性
  switch (type) {
    case 'button':
      // 对于按钮组件，将 text 属性转换为插槽内容，移除 text 属性
      const { text, ...buttonProps } = componentProps
      return {
        ...buttonProps,
        // 确保 size 属性有效
        size: buttonProps.size === 'medium' ? 'default' : buttonProps.size
      }
    case 'image':
      // 对于图片组件，处理 src 和 alt 属性
      return {
        src: componentProps.src || componentProps.url || 'https://via.placeholder.com/300x200',
        alt: componentProps.alt || componentProps.description || '图片描述',
        fit: componentProps.fit || componentProps.fillMethod || 'cover'
      }
    case 'text':
      // 对于文本组件，处理文本内容
      return {
        ...componentProps,
        // 确保文本内容正确显示
        text: componentProps.text || componentProps.content || '文本内容'
      }
    case 'container':
      // 对于容器组件，确保传递 children 属性
      return {
        ...componentProps,
        children: component.children || []
      }
    default:
      return componentProps
  }
}

const handleClick = (event) => {
  event.stopPropagation()
  emit('click', props.component, event)
}

const handleDoubleClick = (event) => {
  event.stopPropagation()
  emit('dblclick', props.component, event)
}

const handleDragStart = (event) => {
  // 如果正在调整大小，则阻止拖拽
  if (isResizing.value) {
    console.log('handleDragStart: 正在调整大小，阻止拖拽')
    event.preventDefault()
    event.stopPropagation()
    return
  }
  
  // 检查鼠标是否在 resize handle 附近（使用状态或实时检测）
  if (isNearResizeHandle.value || isMouseNearResizeHandle(event.clientX, event.clientY)) {
    console.log('handleDragStart: 鼠标在 resize handle 附近，阻止拖拽', {
      isNearResizeHandle: isNearResizeHandle.value,
      mousePos: { x: event.clientX, y: event.clientY },
      componentId: props.component.id
    })
    event.preventDefault()
    event.stopPropagation()
    return
  }
  
  event.stopPropagation()
  
  // 设置拖拽数据
  event.dataTransfer.effectAllowed = 'move'
  event.dataTransfer.setData('application/json', JSON.stringify({
    type: 'move',
    component: props.component,
    source: 'canvas'
  }))
  
  emit('drag-start', props.component, event)
}

const handleDragOver = (event) => {
  event.preventDefault()
  event.stopPropagation()
  
  if (canAcceptDrop.value) {
    isDragOver.value = true
    dragDropManager.setDropTarget(props.component)
    
    // 拖拽时的目标可视化：高亮显示当前拖拽目标
    if (dragDropManager.isDragging.value) {
      // 触发拖拽目标高亮事件
      emit('drag-target-highlight', props.component)
    }
  }
}

const handleDrop = (event) => {
  event.preventDefault()
  event.stopPropagation()
  
  isDragOver.value = false
  
  try {
    const data = JSON.parse(event.dataTransfer.getData('application/json'))
    const { type, component, source } = data
    
    if (type === 'new' && source === 'library') {
      // 添加新组件到当前组件
      emit('update', props.component.id, {
        children: [...(props.component.children || []), component]
      })
    } else if (type === 'move' && source === 'canvas') {
      // 移动组件到当前组件
      // 这里需要从原位置移除，然后添加到当前位置
      // 具体逻辑由父组件处理
    }
  } catch (error) {
    console.error('拖拽数据解析失败:', error)
  }
}

const handleDragLeave = (event) => {
  event.preventDefault()
  event.stopPropagation()
  
  // 检查是否真的离开了组件区域
  const rect = event.currentTarget.getBoundingClientRect()
  const x = event.clientX
  const y = event.clientY
  
  if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) {
    isDragOver.value = false
  }
}

const handleEdit = () => {
  // 触发编辑事件
  emit('update', props.component.id, { isEditing: true })
}

const handleDelete = () => {
  // 触发删除事件
  emit('delete', props.component.id)
}

const handleChildClick = (childComponent, event) => {
  emit('click', childComponent, event)
}

const handleChildDoubleClick = (childComponent, event) => {
  emit('dblclick', childComponent, event)
}

const handleChildDragStart = (childComponent, event) => {
  emit('drag-start', childComponent, event)
}

const handleChildUpdate = (childId, updates) => {
  // 更新子组件
  const updatedChildren = props.component.children?.map(child => 
    child.id === childId ? { ...child, ...updates } : child
  )
  
  emit('update', props.component.id, { children: updatedChildren })
}

const handleChildDelete = (childId) => {
  // 删除子组件
  const updatedChildren = props.component.children?.filter(child => child.id !== childId)
  emit('update', props.component.id, { children: updatedChildren })
}

const isChildSelected = (child) => {
  return selectedComponent.value?.id === child.id
}

// 调整大小相关方法
const startResize = (direction, event) => {
  console.log('startResize: 开始处理调整大小请求', { direction, isPreview: props.isPreview, isResizing: isResizing.value })
  
  // 状态验证：预览模式或已经在调整大小则返回
  if (props.isPreview || isResizing.value) {
    console.log('startResize: 状态检查失败，退出', { isPreview: props.isPreview, isResizing: isResizing.value })
    return
  }
  
  // 事件验证：确保事件对象有效
  if (!event || !event.currentTarget) {
    console.warn('startResize: 无效的事件对象', { direction, event })
    return
  }
  
  // 检查是否与拖拽系统冲突（通过 inject 获取拖拽管理器状态）
  try {
    const dragDropManager = inject('dragDropManager', null)
    if (dragDropManager && dragDropManager.isDragging && dragDropManager.isDragging.value) {
      console.warn('startResize: 检测到拖拽冲突，等待拖拽完成', { direction })
      return
    }
  } catch (error) {
    // 忽略拖拽管理器注入失败
  }
  
  try {
    // 设置调整大小状态
    isResizing.value = true
    resizeDirection.value = direction
    
    // 获取起始位置和尺寸
    // 注意：event.currentTarget 是 resize handle，我们需要获取整个组件的尺寸
    const componentElement = document.querySelector(`[data-component-id="${props.component.id}"]`)
    if (!componentElement) {
      console.error('startResize: 无法找到组件元素', { componentId: props.component.id })
      resetResizeState()
      return
    }
    
    const rect = componentElement.getBoundingClientRect()
    resizeStartPos.value = { x: event.clientX, y: event.clientY }
    
    // 优先使用组件样式中的尺寸，如果没有则使用实际渲染尺寸
    const currentStyle = props.component.style || {}
    resizeStartSize.value = { 
      width: currentStyle.width ? parseFloat(currentStyle.width) : rect.width,
      height: currentStyle.height ? parseFloat(currentStyle.height) : rect.height
    }
    
    // 添加全局事件监听器
    document.addEventListener('mousemove', handleResize)
    document.addEventListener('mouseup', stopResize)
    
    console.log('startResize: 开始调整大小', { 
      direction, 
      startPos: resizeStartPos.value, 
      startSize: resizeStartSize.value,
      componentId: props.component.id,
      currentStyle: currentStyle,
      actualRect: { width: rect.width, height: rect.height }
    })
    
    // 测试：立即触发一次尺寸更新来验证逻辑
    console.log('startResize: 测试立即更新尺寸')
    const testEvent = { clientX: event.clientX, clientY: event.clientY }
    handleResize(testEvent)
    
    // 确保拖拽状态被禁用
    if (event.dataTransfer) {
      event.dataTransfer.effectAllowed = 'none'
    }
  } catch (error) {
    console.error('startResize: 启动调整大小失败', error)
    resetResizeState()
  }
}

const handleResize = (event) => {
  // 调试信息：每次鼠标移动都记录
  console.log('handleResize: 鼠标移动事件', {
    event: event,
    clientX: event?.clientX,
    clientY: event?.clientY,
    isResizing: isResizing.value,
    direction: resizeDirection.value
  })
  
  // 状态一致性验证
  if (!isResizing.value || !resizeDirection.value) {
    console.warn('handleResize: 状态不一致，停止调整大小', { isResizing: isResizing.value, direction: resizeDirection.value })
    stopResize()
    return
  }
  
  // 事件验证
  if (!event || typeof event.clientX !== 'number' || typeof event.clientY !== 'number') {
    console.warn('handleResize: 无效的鼠标事件', event)
    return
  }
  
  try {
    const deltaX = event.clientX - resizeStartPos.value.x
    const deltaY = event.clientY - resizeStartPos.value.y
    
    let newWidth = resizeStartSize.value.width
    let newHeight = resizeStartSize.value.height
    
    // 根据调整方向计算新尺寸
    if (resizeDirection.value.includes('e')) {
      newWidth = Math.max(50, resizeStartSize.value.width + deltaX)
    }
    if (resizeDirection.value.includes('w')) {
      newWidth = Math.max(50, resizeStartSize.value.width - deltaX)
    }
    if (resizeDirection.value.includes('s')) {
      newHeight = Math.max(50, resizeStartSize.value.height + deltaY)
    }
    if (resizeDirection.value.includes('n')) {
      newHeight = Math.max(50, resizeStartSize.value.height - deltaY)
    }
    
    // 更新组件样式
    emit('update', props.component.id, {
      style: {
        ...props.component.style,
        width: `${newWidth}px`,
        height: `${newHeight}px`
      }
    })
    
    // 性能监控：记录调整大小操作
    if (process.env.NODE_ENV === 'development') {
      console.log('handleResize: 尺寸已更新', {
        direction: resizeDirection.value,
        newSize: { width: newWidth, height: newHeight },
        delta: { x: deltaX, y: deltaY }
      })
    }
  } catch (error) {
    console.error('handleResize: 处理调整大小失败', error)
    stopResize()
  }
}

const stopResize = () => {
  try {
    console.log('stopResize: 开始停止调整大小', { 
      componentId: props.component.id,
      wasResizing: isResizing.value 
    })
    
    // 强制清理所有状态
    isResizing.value = false
    resizeDirection.value = ''
    resizeStartPos.value = { x: 0, y: 0 }
    resizeStartSize.value = { width: 0, height: 0 }
    
    // 移除全局事件监听器
    document.removeEventListener('mousemove', handleResize)
    document.removeEventListener('mouseup', stopResize)
    
    console.log('stopResize: 调整大小已停止，状态已清理', { componentId: props.component.id })
  } catch (error) {
    console.error('stopResize: 停止调整大小失败', error)
    // 即使出错也要强制清理状态
    resetResizeState()
  }
}

// 状态管理辅助函数
const resetResizeState = () => {
  console.log('resetResizeState: 强制重置调整大小状态')
  
  // 强制清理所有状态
  isResizing.value = false
  resizeDirection.value = ''
  resizeStartPos.value = { x: 0, y: 0 }
  resizeStartSize.value = { width: 0, height: 0 }
  
  // 强制移除事件监听器（即使可能不存在）
  try {
    document.removeEventListener('mousemove', handleResize)
    document.removeEventListener('mouseup', stopResize)
  } catch (error) {
    // 忽略移除监听器时的错误
  }
}

// 检查鼠标是否在 resize handle 附近
const isMouseNearResizeHandle = (mouseX, mouseY) => {
  if (!props.isSelected) return false
  
  try {
    const element = document.querySelector(`[data-component-id="${props.component.id}"]`)
    if (!element) return false
    
    const rect = element.getBoundingClientRect()
    const handleSize = 20 // 增加检测区域大小，提供更好的用户体验
    
    // 检查四个角落的 resize handle 区域
    const handleAreas = [
      // 左上角 (nw) - 扩大检测区域
      {
        left: rect.left - handleSize/2,
        top: rect.top - handleSize/2,
        right: rect.left + handleSize/2,
        bottom: rect.top + handleSize/2
      },
      // 右上角 (ne) - 扩大检测区域
      {
        left: rect.right - handleSize/2,
        top: rect.top - handleSize/2,
        right: rect.right + handleSize/2,
        bottom: rect.top + handleSize/2
      },
      // 左下角 (sw) - 扩大检测区域
      {
        left: rect.left - handleSize/2,
        top: rect.bottom - handleSize/2,
        right: rect.left + handleSize/2,
        bottom: rect.bottom + handleSize/2
      },
      // 右下角 (se) - 扩大检测区域
      {
        left: rect.right - handleSize/2,
        top: rect.bottom - handleSize/2,
        right: rect.right + handleSize/2,
        bottom: rect.bottom + handleSize/2
      }
    ]
    
    // 检查鼠标是否在任何 handle 区域内
    const isNear = handleAreas.some(area => 
      mouseX >= area.left && mouseX <= area.right && 
      mouseY >= area.top && mouseY <= area.bottom
    )
    
    // 调试信息
    if (process.env.NODE_ENV === 'development' && isNear) {
      console.log('isMouseNearResizeHandle: 检测到鼠标在 handle 附近', {
        mousePos: { x: mouseX, y: mouseY },
        handleAreas,
        componentId: props.component.id
      })
    }
    
    return isNear
  } catch (error) {
    console.warn('isMouseNearResizeHandle: 检测失败', error)
    return false
  }
}

// 状态一致性检查
const validateResizeState = () => {
  const isValid = isResizing.value && 
                  resizeDirection.value && 
                  resizeStartPos.value.x !== 0 && 
                  resizeStartPos.value.y !== 0 &&
                  resizeStartSize.value.width !== 0 && 
                  resizeStartSize.value.height !== 0
  
  if (!isValid && isResizing.value) {
    console.warn('validateResizeState: 检测到不一致的状态，正在清理', {
      isResizing: isResizing.value,
      direction: resizeDirection.value,
      startPos: resizeStartPos.value,
      startSize: resizeStartSize.value
    })
    resetResizeState()
  }
  
  return isValid
}

// 生命周期
onMounted(() => {
  // 组件挂载后的初始化逻辑
  console.log('ComponentRenderer: 组件已挂载', { componentId: props.component.id })
})

onUnmounted(() => {
  // 强制清理所有状态和事件监听器
  console.log('ComponentRenderer: 组件即将卸载，清理资源', { componentId: props.component.id })
  
  if (isResizing.value) {
    console.warn('ComponentRenderer: 组件卸载时仍在调整大小，强制清理')
    resetResizeState()
  }
  
  // 确保事件监听器被移除
  try {
    document.removeEventListener('mousemove', handleResize)
    document.removeEventListener('mouseup', stopResize)
  } catch (error) {
    // 忽略清理时的错误
  }
})
</script>

<style scoped>
.component-renderer {
  position: relative;
  display: inline-block;
  max-width: 100%;
  min-width: 20px;
  min-height: 20px;
  border: none; /* 移除默认边框，避免两个红色边框之间的间距 */
  transition: all 0.2s ease;
  user-select: none;
  border-radius: 2px; /* 添加圆角 */
}

.component-renderer:hover {
  border-color: #e4e7ed; /* 更淡的hover边框 */
  background-color: rgba(64, 158, 255, 0.02); /* 更淡的背景 */
}

.component-renderer.is-selected {
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.3); /* 更粗的选中边框 */
  background-color: rgba(64, 158, 255, 0.05); /* 选中时的背景色 */
}

/* 当鼠标在 resize handle 附近时，禁用拖拽的视觉反馈 */
.component-renderer.is-selected.is-near-resize-handle {
  cursor: default !important;
}

.component-renderer.is-selected.is-near-resize-handle .component-content {
  cursor: default !important;
}

.component-renderer.is-dragging {
  opacity: 0.6;
}

.component-renderer.is-drag-over {
  border-color: #409eff;
  background-color: rgba(64, 158, 255, 0.1);
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.4);
}

.component-renderer.is-preview {
  border: none;
  box-shadow: none;
}

.component-renderer.is-preview:hover {
  border-color: transparent;
}

/* 选择边框 */
.component-selection-border {
  position: absolute;
  top: -2px;
  left: -2px;
  right: -2px;
  bottom: -2px;
  pointer-events: none;
  z-index: 1000;
}

/* 选中指示器 */
/* .selection-indicator {
  position: absolute;
  top: -8px;
  left: -8px;
  display: flex;
  align-items: center;
  gap: 4px;
  background: rgba(64, 158, 255, 0.95);
  color: white;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  z-index: 1001;
} */

.indicator-dot {
  width: 6px;
  height: 6px;
  background: white;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

.indicator-text {
  white-space: nowrap;
}

/* 层级信息显示 */
.layer-info {
  position: absolute;
  top: -8px;
  right: -8px;
  z-index: 1001;
}

.layer-badge {
  background: rgba(103, 194, 58, 0.95);
  color: white;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);
}

.selection-handles {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.handle {
  position: absolute;
  width: 8px;
  height: 8px;
  background: #409eff;
  border: 1px solid white;
  border-radius: 50%;
  pointer-events: all;
  cursor: pointer;
}

.handle:hover {
  background: #66b1ff;
  transform: scale(1.2);
}

.handle-nw {
  top: -4px;
  left: -4px;
  cursor: nw-resize;
}

.handle-ne {
  top: -4px;
  right: -4px;
  cursor: ne-resize;
}

.handle-sw {
  bottom: -4px;
  left: -4px;
  cursor: sw-resize;
}

.handle-se {
  bottom: -4px;
  right: -4px;
  cursor: se-resize;
}

/* 组件内容 */
.component-content {
  height: 100%;
  position: relative;
}

/* 组件标签 */
.component-label {
  position: absolute;
  top: -13px;
  left: 2px;
  height: 20px;
  background: transparent;
  color: white;
  font-size: 11px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding: 0;
  opacity: 1;
  transition: opacity 0.2s ease;
  pointer-events: none;
  z-index: 1000;
}

/* 子组件的标签应该有更高的z-index */
.component-renderer .component-renderer .component-label {
  z-index: 1001;
}

/* 更深层级的子组件标签 */
.component-renderer .component-renderer .component-renderer .component-label {
  z-index: 1002;
}

/* 移除原来的hover效果，现在由JavaScript控制 */
/* .component-renderer:hover .component-label,
.component-renderer.is-selected .component-label {
  opacity: 1;
} */

/* 选中状态的标签样式 */
.component-renderer.is-selected .component-label {
  opacity: 1;
}

.component-renderer.is-selected .component-label .label-text {
  background: rgba(64, 158, 255, 1);
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.3);
}

.label-text {
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  background: rgba(64, 158, 255, 0.9);
  padding: 2px 6px;
  border-radius: 3px;
  margin-right: 4px;
}

.label-actions {
  display: flex;
  gap: 2px;
  pointer-events: all;
}

.label-actions .el-button {
  padding: 2px 4px;
  font-size: 10px;
  color: white;
  background: rgba(64, 158, 255, 0.9);
  border-radius: 3px;
  margin-left: 4px;
}

.label-actions .el-button:hover {
  color: #f0f0f0;
}

/* 拖拽高亮 */
.drag-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(64, 158, 255, 0.1);
  border: 2px dashed #409eff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1001;
}



.drop-zone {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: #409eff;
  font-size: 12px;
}

.drop-zone i {
  font-size: 24px;
}

/* 组件类型特定样式 */
.component-container {
  border: 1px dashed #dcdfe6;
  background: rgba(245, 245, 245, 0.5);
  min-height: 60px;
  padding: 0; /* 移除padding */
}

.component-container:hover {
  border-color: #409eff;
  background: rgba(64, 158, 255, 0.05);
}

.component-text {
  padding: 0; /* 移除padding */
  min-height: 20px;
  display: flex;
  align-items: center;
}

.component-button {
  padding: 0; /* 移除padding */
  border-radius: 4px;
  text-align: center;
  cursor: pointer;
}

.component-input,
.component-textarea,
.component-select {
  padding: 0; /* 移除padding */
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  min-height: 32px;
}

.component-image {
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  color: #909399;
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .component-label {
    font-size: 10px;
    padding: 0 4px;
  }
  
  .handle {
    width: 6px;
    height: 6px;
  }
}
</style> 